from openpyxl import load_workbook
from openpyxl.utils.exceptions import InvalidFileException
from util_tools.logs_util.recordlog import logs
import os

class ExcelDataReader:

    def __init__(self, file_path):
        self.file_path = file_path
        abspath = os.path.abspath(self.file_path)
        if not os.path.isfile(abspath):
            raise FileNotFoundError(f'文件路径不存在：{abspath}')
        self.workbook = load_workbook(self.file_path, read_only=False)

    def read_entire_row(self, sheet_name='Sheet1', row_index=1):
        try:
            sheet = self.workbook[sheet_name]
            # 列表推导式
            rows_data = [cell.value for cell in sheet[row_index]]
            return rows_data
        except Exception as e:
            logs.error(f'读取Excel文件一整行的数据数据异常，原因为：{e}')
        finally:
            self.close()

    def read_multiple_rows(self, sheet_name='Sheet1'):
        try:
            all_rows_data = []
            sheet = self.workbook[sheet_name]
            max_col = sheet.max_column

            for row in sheet.iter_rows(min_row=1, max_row=sheet.max_row, min_col=1, max_col=max_col):
                row_data = [cell.value for cell in row]
                all_rows_data.append(row_data)
            return all_rows_data
        except Exception as e:
            logs.error(f'读取所有行数据异常，原因为：{e}')
        finally:
            self.close()

    def read_entire_column(self, sheet_name='Sheet1', column_index=1):
        column_data = []
        try:
            sheet = self.workbook[sheet_name]
            for row in sheet.iter_rows(min_row=1, min_col=column_index, max_col=column_index):
                column_data.append(row[0].value)
            return column_data
        except Exception as e:
            logs.error(f'读取整列数据异常，原因为：{e}')
        finally:
            self.close()

    def read_cell_value(self, row_index, column_index, sheet_name='Sheet1'):
        try:
            sheet = self.workbook[sheet_name]
            return sheet.cell(row=row_index, column=column_index).value
        except Exception as e:
            logs.error(f'读取单元格数据异常，原因为：{e}')
        finally:
            self.close()

    def close(self):
        """关闭文件操作（释放内存空间资源）"""
        self.workbook.close()


# 调试查看
if __name__ == '__main__':
    # 实例化类--里面是文件路径
    exl = ExcelDataReader('../../data/login_test.xlsx')
    print(exl.read_cell_value(row_index=4, column_index=2))